<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/4/5
 * Time: 15:49
 */

namespace App\Http\Controllers;


use App\Models\AwardLog;
use App\Models\CardSeries;
use App\Models\UserDrawLotsLog;
use App\Repos\CardRepo;
use App\Repos\MemberRepo;
use App\Repos\MessageRepo;
use App\Services\DrawLotsService;
use App\Transformers\CardSeriesAwardTransformer;
use App\Transformers\CardSeriesTransformer;
use App\Transformers\CardTransformer;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class DrawLotsController extends ApiController
{
    protected $drawLotsService;
    private $config;
    private $draw_lots_config;

    public function __construct(DrawLotsService $dls)
    {
        parent::__construct();
        $this->drawLotsService = $dls;
        $this->config = config('car.merchant_config');
        $this->draw_lots_config = config('car.draw_lots_config');
    }

    //签到首页
    public function drawLots(CardTransformer $cardTransformer)
    {
        //签到天数
        $days = $this->user->checkInNum ?: 0;

        $is_checked = (int)$this->drawLotsService::checkSignStatus($this->user->id);

        //卡牌
        $series_cards_info = CardSeries::get()->transform(function ($item) use ($cardTransformer) {
            $data = (new CardSeriesTransformer())->singleData($item);

            $cards = $item->cards()->orderByDesc('sort')->get()->transform(function ($item) use ($cardTransformer) {
                $card = $cardTransformer->singleData($item);
                $cardLog = UserDrawLotsLog::where('user_id', $this->user->id)
                    ->where('card_id', $item->id)
                    ->orderBy('id')
                    ->first();
                $card['hold'] = (int)(bool)$cardLog;
                $card['is_new'] = $cardLog ? (int)(Carbon::parse($cardLog->created_at)->toDateString() >= Carbon::today()->subDays(3)->toDateString()) : 0;
                return $card;
            });
            $rewards = $item->awards() ? (new CardSeriesAwardTransformer())->listData($item->awards()->get()) : [];
            $data['hold'] = UserDrawLotsLog::distinct('card_id')
                ->where('user_id', $this->user->id)
                ->where('card_series_id', $item->id)
                ->count('card_id');
            $data['cards'] = $cards;
            $data['rewards'] = $rewards;
            $data['is_full'] = (int)CardRepo::checkIsFull($this->user->id, $item->id);
            return $data;
        });

        return $this->success(compact('days', 'is_checked', 'series_cards_info'));
    }

    //签到首页
    public function sign_status()
    {
        //签到天数
        $days = (int)($this->user->checkInNum ?: 0);

        $is_signed = (int)$this->drawLotsService::checkSignStatus($this->user->id);

        return compact('days', 'is_signed');
    }

    //新增用户(对外)
    public function add_user()
    {
        $cache_name = 'user_token_' . $this->request->input('user_token');
        $remote_user_id = Cache::get($cache_name);
        if ($remote_user_id) {
            $member = MemberRepo::findUserForRemote($remote_user_id);
            if ($member)
                $status = 'success';
            else
                $status = 'fail';
            return compact('status', 'member');
        } else {
            $status = 'fail';
            return compact('status');
        }
    }

    //减扣金币接口(对外)
    public function decrementUserGold()
    {
        $gold = $this->request->input('gold');
        $user_id = $this->user->id;
        if (!isset($gold))
            $gold = $this->config['gold'];
        $bool = MemberRepo::decrementUserCredit($this->user, $this->config['gold']);
        if ($bool)
            $status = 'success';
        else
            $status = 'fail';
        //if(env('APP_DEBUG'))Log::info('api '.$status.':'.json_encode(compact('user_id','status','gold')));
        return compact('user_id', 'status', 'gold');
    }

    //增加金币接口(对外)
    public function incrementUserGold()
    {
        $gold = $this->request->input('gold');
        $user_id = $this->user->id;
        if (!isset($gold))
            $gold = $this->config['gold'];
        //$gold=$this->config['gold'];
        $bool = MemberRepo::incrementUserGold($this->user, $this->config['gold']);
        if ($bool)
            $status = 'success';
        else
            $status = 'fail';
        // if(env('APP_DEBUG'))Log::info('api '.$status.':'.json_encode(compact('user_id','status','gold')));
        return compact('user_id', 'status', 'gold');
    }

    //领取卡牌
    public function card(CardTransformer $cardTransformer)
    {
        $today_log = UserDrawLotsLog::where(['user_id' => $this->user->id])
            ->whereDate('created_at', date('Y-m-d'))->first();

        if (!$today_log) {
            return $this->error(1, '还未签到，不能领取');
        }

        if (null !== $today_log['card_id']) {
            return $this->error(1, '已经领取过');
        }

        $card = $this->drawLotsService::getRandomCard($this->user->id);
        if (!$card) {
            return $this->error(1, '很遗憾，未领取到卡片');
        }
        $card_log = UserDrawLotsLog::where('user_id', $this->user->id)
            ->where('card_id', $card->id)
            ->where('card_series_id', $card->card_series_id)
            ->exists();
        $is_new = (int)!$card_log;

        $today_log->card_id = $card->id;
        $today_log->card_series_id = $card->card_series_id;
        $today_log->save();

        $card_info = $cardTransformer->singleData($card);

        $card_info['hold'] = 1;

        $card_info['is_new'] = $is_new;

        return $this->success($card_info);
    }


    //领取卡牌-分开
    public function draw_card(CardTransformer $cardTransformer)
    {
        if (empty($this->card_series_id)) {
            return $this->error(3, '参数不正确');
        }
        $today_draw_count = UserDrawLotsLog::where(['user_id' => $this->user->id])
            ->whereDate('created_at', date('Y-m-d'))->count();

        $today_log = UserDrawLotsLog::where(['user_id' => $this->user->id])->where(['card_series_id' => $this->card_series_id])
            ->whereDate('created_at', date('Y-m-d'))->first();

        if ($today_draw_count >= $this->draw_lots_config['draw_lots_num']) {
            return $this->error(1, '已达到最大抽卡次数');
        }

        if (null !== $today_log['card_series_id']) {
            return $this->error(2, '已经领取过');
        }

        $card = $this->drawLotsService::getCard($this->user->id, $this->card_series_id);
        if (!$card) {
            return $this->error(1, '很遗憾，未领取到卡片');
        }
        $card_log = UserDrawLotsLog::where('user_id', $this->user->id)
            ->where('card_id', $card->id)
            ->where('card_series_id', $card->card_series_id)
            ->exists();
        $is_new = (int)!$card_log;
        $today_log = new UserDrawLotsLog();
        $today_log->card_id = $card->id;
        $today_log->card_series_id = $card->card_series_id;
        $today_log->user_id = $this->user->id;
        $today_log->lucky_type = 0;
        $today_log->save();

        $card_info = $cardTransformer->singleData($card);

        $card_info['hold'] = 1;

        $card_info['is_new'] = $is_new;

        return $this->success($card_info);
    }

    //卡套list
    public function card_series()
    {
        $card_series = $this->drawLotsService::get_card_series();
        foreach ($card_series as $card_serie) {
            $today_log = UserDrawLotsLog::where(['user_id' => $this->user->id])->where('card_series_id', $card_serie->id)
                ->whereDate('created_at', date('Y-m-d'))->first();
            if ($today_log)
                $card_serie->isDrawed = true;

            else
                $card_serie->isDrawed = false;
        }
        return $this->success($card_series);
    }

    //执行签到
    public function signIn()
    {
        $check_info = $this->drawLotsService->drawLots($this->user->id);
        return $this->success($check_info);
    }

    public function rewards(MemberRepo $memberRepo)
    {
        //return $this->error(1,'领取失败');
        $card_series_id = $this->request->id;
        if (empty($card_series_id)) {
            return $this->error(1, '领取失败，参数错误');
        }

        //是否已经领取过此奖励
        $exists = AwardLog::where('user_id', $this->user->id)->where('card_series_id', $card_series_id)->where('status', 1)->exists();
        if ($exists)
            return $this->error(1, '您已经领过此奖励');

        //判断是否集齐
        $full = CardRepo::checkIsFull($this->user->id, $card_series_id);
        if (!$full)
            return $this->error(1, '您还未集齐所有卡片');

        //获取奖励
        $card_series = CardSeries::findOrFail($card_series_id);

        $new_log = new AwardLog();
        $new_log->card_series_id = $card_series_id;
        $new_log->user_id = $this->user->id;
        $new_log->status = 1;
        $re = $new_log->save();

        if ($re) {
            $awards = $card_series->awards()->get();

            if ($awards->isEmpty()) {
                return $this->error(1, '此系列暂无奖励');
            }

            $awards->map(function ($item) use ($memberRepo, $card_series) {
                switch ($item->award_category) {
                    case 1:
                        //发放金币
                        if ($memberRepo->incrementUserCredit($this->user, $item->award_extra)) {
                            MessageRepo::push([
                                'type' => 1,
                                'user_id' => $this->user->id,
                                'to_user_id' => $this->user->id,
                                'text' => sprintf(config('words.messages.fulfill_card_series'), $card_series->name, $item->award_extra),
                                'record_id' => $card_series->id,
                            ]);
                        }

                        break;
                    case 2:
                        //发放积分
                        $memberRepo->incrementUserRemoteScoreForCard($this->user, $item->award_extra);
                        break;
                    case 3:
                        //TODO::框-未定义
                        break;
                    case 4:
                        //TODO::勋章-未定义
                        break;
                }
            });


            return $this->success('奖励已成功发放至账户');
        }

        return $this->error(1, '领取失败');
    }

}